// 存储localStorage
export const setStorage = (name, content) => {
  if (!name) return
  if (typeof content !== 'string') {
    content = JSON.stringify(content)
  }
  window.localStorage.setItem(name, content)
}

// 获取localStorage
export const getStorage = name => {
  let historyArray = window.localStorage.getItem(name)
  try {
    historyArray = JSON.parse(historyArray)
  } catch (error) {
    historyArray = []
  }
  return Promise.resolve(historyArray)
}

// 删除localStorage
export const removeStorage = name => {
  if (!name) return
  let bStop
  try {
    window.localStorage.removeItem(name)
    bStop = true
  } catch (error) {
    bStop = false
  }
  return Promise.resolve(bStop)
}

// 存历史记录localStorage
export const saveHistory = searchData => {
  let oldSearchData = JSON.parse(
    window.localStorage.getItem('searchData')
      ? window.localStorage.getItem('searchData')
      : '[]'
  )
  let searchArr = []
  for (let key in oldSearchData) {
    if (searchData.id !== oldSearchData[key].id) {
      searchArr.push(oldSearchData[key])
    }
  }
  searchArr.unshift(searchData)
  // oldSearchData = { ...searchArr }
  setStorage('searchData', searchArr)
}
